package com.test.shiver.controller;

import com.test.shiver.entity.User;
import com.test.shiver.service.UserService;
import com.test.shiver.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserAddServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String userId = request.getParameter("id");
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();
        if(userId !=null && !userId.equals("")){
            user.setId(Integer.parseInt(userId));
        }
        user.setUsername(userName);
        user.setPassword(password);
        int ret = -1;
        String msg = "";
        if(userId==null || userId.equals("")){
            System.out.println("1");
            ret = userService.addUser(user);
            if(ret != -1){
                msg = "更新成功";
            }else{
                msg = "更新失败";
            }
        }else{
            if(userService.getUserById(Integer.parseInt(userId)) != null){
                System.out.println("2");
                ret = userService.updateUser(user);
                if(ret != -1){
                    msg = "更新成功";
                }else{
                    msg = "更新失败";
                }
            }
        }

        request.setAttribute("msg",msg);
        request.getRequestDispatcher("/userList").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request,response);
    }
}
